<template>
  <a-drawer
    title="生成账单"
    :width="1355"
    :visible="visible"
    :body-style="{ paddingBottom: '80px' }"
    @close="onClose"
    :maskClosable="false"
  >
    <div class="drawer_con">
      <div class="top_con">
        <div class="left_form">
          <div class="standard_con">
            <div
              class="standard_list"
              v-for="(item, index) in topList"
              :key="index"
            >
              <div class="left_label">{{ item.label }}：</div>
              <div class="right_value">{{ item.value }}</div>
            </div>
          </div>
          <div class="form_con">
            <a-form
              :model="standardForm"
              ref="formRef"
              :rules="rules"
              layout="vertical"
            >
              <div class="form_title">基本信息</div>
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="费用类型" name="fee_type">
                    <a-cascader
                      v-model:value="standardForm.fee_type"
                      :options="costTypeList"
                      placeholder="请选择费用类型"
                      :load-data="getCostTypeSub"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="收费标准名称" name="standard_name">
                    <a-input
                      :disabled="true"
                      v-model:value="standardForm.standard_name"
                      placeholder="请输入"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item name="price_or_amount">
                    <template #label>
                      <div
                        style="display: flex; flex-wrap: nowrap; width: 288px"
                      >
                        <div style="width: 60%"><span>单价（元)</span></div>
                        <div style="width: 40%"><span>计算单位</span></div>
                      </div>
                    </template>
                    <a-input
                      :disabled="true"
                      style="width: 60%"
                      v-model:value="standardForm.price_or_amount"
                      placeholder="请输入"
                    />
                    <a-form-item-rest>
                      <a-select
                        style="width: 40%"
                        placeholder="请选择"
                        @change="
                          (value) => handleSelectChange(value, 'unit_charging')
                        "
                        v-model:value="standardForm.unit_charging"
                      >
                        <template v-if="standardForm.cash_type == 2 && standardForm.mode == 1">
                          <a-select-option
                              v-for="(key, value) in unitOnceRelation['1']"
                              :key="value"
                              :value="value"
                          >{{ key }}</a-select-option >
                        </template>
                        <template v-if="standardForm.cash_type == 2 && standardForm.mode == 2">
                          <a-select-option
                              v-for="(key, value) in unitOnceRelation['2']"
                              :key="value"
                              :value="value"
                          >{{ key }}</a-select-option >
                        </template>
                        <template v-if="standardForm.cash_type == 1 && standardForm.mode == 1">
                          <a-select-option
                              v-for="(key, value) in unitYuanRelation['1']"
                              :key="value"
                              :value="value"
                          >{{ key }}</a-select-option >
                        </template>
                        <template v-if="standardForm.cash_type == 1 && standardForm.mode == 2">
                          <a-select-option
                              v-for="(key, value) in unitYuanRelation['2']"
                              :key="value"
                              :value="value"
                          >{{ key }}</a-select-option >
                        </template>
                      </a-select>
                    </a-form-item-rest>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col v-if="standardForm.cash_type == 1" :span="8">
                  <a-form-item name="pay_date_days">
                    <template #label>
                      <div
                        style="display: flex; flex-wrap: nowrap; width: 288px"
                      >
                        <div style="width: 40.3%; flex-shrink: 0">
                          <span style="margin-right: 10px">付款时间</span>
                          <a-tooltip placement="topLeft">
                            <template #title>
                              付款时间计算规则(含当天)。<br />
                              1、按开始延后 （表示是按照账单的开始时间进行延后
                              N个自然日或工作日）<br />
                              2、按结束延后 （表示是按照账单的结束时间进行延后
                              N个自然日或工作日）<br />
                              3、提前 （表示是按照账单的开始时间进行提前
                              N个自然日或工作日）<br />
                              4、指定日期
                              （表示是按照账单的开始时间进行从本月起或者不计算本月进行延后）<br />
                            </template>
                            <QuestionCircleOutlined />
                          </a-tooltip>
                        </div>
                        <div style="width: 26.3%; flex-shrink: 0">
                          <span></span>
                        </div>
                        <div style="width: 33.3%; flex-shrink: 0">
                          <span>日期计算方式</span>
                        </div>
                      </div>
                    </template>
                    <div class="form_item">
                      <a-form-item-rest>
                        <div style="width: 40.3%">
                          <a-select
                            placeholder="请选择"
                            v-model:value="standardForm.pay_date_action"
                            @change="
                              (value) =>
                                handleSelectChange(value, 'pay_date_action')
                            "
                          >
                            <a-select-option
                              v-for="(key, value) in payActionDayArr"
                              :key="value"
                              :value="value"
                              >{{ key }}</a-select-option
                            >
                          </a-select>
                        </div>
                      </a-form-item-rest>

                      <a-input-number
                        :min="1"
                        :max="366"
                        style="width: 26.3%"
                        placeholder="请输入"
                        v-model:value="standardForm.pay_date_days"
                      />
                      <a-form-item-rest>
                        <a-select
                          v-if="standardForm.pay_date_action != 'specify_date'"
                          style="width: 33.3%"
                          placeholder="请选择"
                          v-model:value="standardForm.pay_date_action_type"
                        >
                          <a-select-option
                            v-for="(key, value) in payDateSelect['delay']"
                            :key="value"
                            :value="value"
                            >{{ key }}</a-select-option
                          >
                        </a-select>
                        <a-select
                          v-else
                          style="width: 33.3%"
                          placeholder="请选择"
                          v-model:value="standardForm.pay_date_action_type"
                        >
                          <a-select-option
                            v-for="(key, value) in payDateSelect[
                              'specify_date'
                            ]"
                            :key="value"
                            :value="value"
                            >{{ key }}</a-select-option
                          >
                        </a-select>
                      </a-form-item-rest>
                    </div>
                  </a-form-item>
                </a-col>
                <a-col v-if="standardForm.cash_type == 1" :span="8">
                  <a-form-item label="缴费时间" name="payment_time">
                    <a-range-picker
                      :disabled-date="disabledDate"
                      style="width: 100%"
                      @change="handleDateChange"
                      v-model:value="standardForm.payment_time"
                      :ranges="dateRanges"
                    />
                  </a-form-item>
                </a-col>
                <a-col v-if="standardForm.cash_type == 2" :span="8">
                  <a-form-item label="缴费时间" name="payment_time">
                    <a-date-picker
                        :disabled-date="disabledDate"
                        style="width: 100%"
                        @change="handleDateChangees"
                        v-model:value="standardForm.payment_time[0]"
                    />
                  </a-form-item>
                </a-col>
                <a-col v-if="standardForm.cash_type == 2" :span="8">
                  <a-form-item label="数量" name="number">
                    <a-input-number
                        id="inputNumber"
                        style="width: 100%"
                        placeholder="请填写数量"
                        v-model:value="standardForm.number"
                        :min="1" />
                  </a-form-item>
                </a-col>
                <a-col v-if="standardForm.cash_type == 1" :span="8">
                  <a-form-item name="daily_unit_price_and_month_rule">
                    <template #label>
                      <div style="margin-right: 10px">计费(和拆分)规则</div>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          选项一【按自然月天数计算】根据本月的实际天数来计算收取的费用。<br />
                          说明 :按本月的实际天数来计算费用金额。
                          根据每月的实际天数计算费用。若收费足月的情况下，两者没有区别；不足月的情况下，计算每一天的费用则不同。比如：只有10天(*平方米)的收费，则10天(*平方米)的费用金额=本月总金额/本月实际天数*10(*平方米)。<br />
                          <br />
                          选项二【按30天/月计算】始终安装每月30天来计算收取的费用。
                        </template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </template>
                    <a-select
                      placeholder="请选择计费规则"
                      v-model:value="
                        standardForm.daily_unit_price_and_month_rule
                      "
                      v-if="refreshSelect"
                      @change="
                        (value) => handleSelectChange(value, 'month_rule')
                      "
                    >
                      <a-select-option value="30_day"
                        >按30天计费</a-select-option
                      >
                      <a-select-option value="month_day"
                        >按自然月{{
                          standardForm.unit_charging == "yuan_per_day" ||
                          standardForm.unit_charging ==
                            "yuan_square_meter_times_per_day"
                            ? "天数"
                            : ""
                        }}计费</a-select-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="账单备注" name="remark">
                    <a-textarea
                        v-model:value="standardForm.remark"
                        placeholder="请输入账单备注"
                        :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <div v-if="standardForm.cash_type == 1" class="form_title">账单拆分/预缴设置</div>
              <a-row v-if="standardForm.cash_type == 1" :gutter="16">
                <a-col :span="8">
                  <a-form-item name="pay_cycle">
                    <template #label>
                      <div style="margin-right: 10px">
                        账单拆分周期（<span
                          style="color: red; font-weight: bolder"
                          >{{
                            standardForm.pay_cycle
                              ? standardForm.pay_cycle
                              : "1"
                          }}</span
                        >月一笔）
                      </div>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          <span
                            v-if="
                              standardForm.daily_unit_price_and_month_rule ==
                              'month_day'
                            "
                          >
                            例：一年的欠费账单（2023-01-01至2023-12-30），按5月一笔拆分，可拆分成3笔账单：<br />
                            第一笔的账单时间2023-01-01至2023-05-31（5个月的账单），<br />
                            第二笔的账单时间2023-06-01至2023-10-31（5个月的账单），<br />
                            第三笔的账单时间2023-11-01至2023-12-31（2个月的账单）。<br />
                          </span>
                          <span v-else>
                            例：一年的欠费账单（2023-01-01至2023-12-30），按5月一笔拆分，可拆分成3笔账单：<br />
                            第一笔的账单时间2023-01-01至2023-05-30（5个月的账单），<br />
                            第二笔的账单时间2023-05-31至2023-10-28（5个月的账单），<br />
                            第三笔的账单时间2023-10-29至2023-12-31（2个月+4天的账单）。<br />
                          </span>
                        </template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </template>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                      "
                    >
                      <div
                        style="
                          width: 10%;
                          height: 33px;
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          background: #eee;
                        "
                      >
                        <FieldTimeOutlined />
                      </div>
                      <a-input-number
                        :min="1"
                        :max="360"
                        style="width: 70%"
                        v-model:value="standardForm.pay_cycle"
                        placeholder="请输入"
                      />
                      <div
                        style="
                          width: 20%;
                          height: 33px;
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          background: #eee;
                        "
                      >
                        {{
                          standardForm.daily_unit_price_and_month_rule ==
                          "month_day"
                            ? "自然月"
                            : "30天/月"
                        }}
                      </div>
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    label="划分方式"
                    name="divide_method"
                    v-if="
                      standardForm.daily_unit_price_and_month_rule ==
                      'month_day'
                    "
                  >
                    <a-select
                      placeholder="请选择划分方式"
                      v-model:value="standardForm.divide_method"
                    >
                      <a-select-option
                        v-for="(key, value) in monthDivideMethodArr"
                        :key="value"
                        :value="value"
                        >{{ key }}</a-select-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
        <!-- 选择绑定房间 -->
        <div
          class="right_single"
          v-if="visible && standardInfo.bind_object == 1"
        >
          <div class="form_title">
            <div class="left_label">请勾选房源</div>
            <div class="right_con">
              <a-button
                type="link"
                @click="changeHouseCard"
                v-if="roomList.length"
              >
                {{ showSelectedHouse ? "选择房源" : "查看已选" }}
              </a-button>
            </div>
          </div>
          <ChooseHousingResources
            v-show="!showSelectedHouse"
            :defaultChecked="{ roomList }"
            :defaultCheckedIds="defaultCheckedIds"
            :areaEmptyDisabled="false"
            limitType="village"
            :defaultShowVillageIds="[standardInfo.village_id]"
            @request="$utils.commonRequest"
            @getResult="getRoomList"
            @getloading="getloading"
            :clauseType="clauseType"
            :allDisabled="chooseHousingDisabled"
          />
          <CheckedHousingResources
            v-show="showSelectedHouse"
            :houseList="roomList"
            :maxTotal="false"
            :includeSelfArea="includeSelfArea"
          />
        </div>
        <!-- 绑定车位 -->
        <div
          class="right_single"
          v-if="visible && standardInfo.bind_object == 2"
        >
          <div class="form_title">
            <div class="left_label">请勾选车位</div>
            <div class="right_con">
              <a-button
                type="link"
                @click="showSelectedPosition = !showSelectedPosition"
                v-if="parkSpaceList.length"
              >
                {{ showSelectedPosition ? "选择车位" : "查看已选" }}
              </a-button>
            </div>
          </div>
          <verticalPosition
            :standardInfo="standardInfo"
            v-show="!showSelectedPosition"
            @setPosition="setPosition"
            :villageId="standardInfo.village_id"
          />
          <positionList
            v-show="showSelectedPosition"
            :parkSpaceList="parkSpaceList"
          />
        </div>
      </div>
      <div class="bottom_con">
        <div class="form_title">账单预览 <span v-if="isDemonstrate">(非真正账单)</span> </div>
        <a-table
          @expand="handleTableExtend"
          :expandedRowKeys="expandedRowKeys"
          :customRow="handleClickRow"
          :scroll="{ x: 'max-content' }"
          v-if="visible"
          rowKey="key"
          :loading="tableLoading"
          :dataSource="tableList"
          :columns="tableColumns"
          :pagination="false"
        >
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'area_range'">
              <a-tag
                v-if="record.type == 'parent' || record.whichStage"
                :bordered="false"
                color="green"
                >{{ record.whichStage }}</a-tag
              >
              <cu-icon
                v-else
                type="org-fenzhi"
                style="font-size: 18px"
              ></cu-icon>
              <span
                >{{ record.startDate }} <SwapRightOutlined />{{
                  record.endDate
                }}
              </span>
            </template>
          </template>
        </a-table>
        <div
          class="table_footer"
          v-if="tableList &&
            tableList.length > 0 &&
            (extionsInfo.costReceivable ||
              extionsInfo.countDays ||
              extionsInfo.unit)
          "
        >
          <div class="footer_left">总计</div>
          <div class="footer_right">
            <div class="footer_item" v-if="extionsInfo.costReceivable">
              费用应收总计: {{ extionsInfo.costReceivable || 0 }}元
            </div>
            <div class="footer_item" v-if="extionsInfo.countDays && standardForm.cash_type == 1">
              总天数: {{ extionsInfo.countDays || 0 }}天
            </div>
            <div class="footer_item" v-if="extionsInfo.unit">
              <span v-if="isDemonstrate">演示</span>平方米: {{ extionsInfo.unit || 0 }}㎡
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'center',
        zIndex: 1,
      }"
    >
      <a-button
        v-if="!confirmLoading"
        style="margin-right: 8px"
        @click="onClose"
        >取消</a-button
      >
      <a-button
        type="primary"
        @click="handleSubmit"
        :disabled="confirmLoading || butloading || constructloading"
        >{{ confirmLoading ? "生成中..." : "开始生成账单" }}</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import request from "../../../../common/utils/request";
import { message } from "ant-design-vue";
import {
  ChooseHousingResources,
  CheckedHousingResources,
} from "bl-common-vue3";
import {
  PlusOutlined,
  CheckOutlined,
  QuestionCircleOutlined,
  FieldTimeOutlined,
  SwapRightOutlined,
} from "@ant-design/icons-vue";
import {
  defineComponent,
  reactive,
  ref,
  watch,
  toRefs,
  nextTick,
  computed,
} from "vue";
import moment from "moment";
import verticalPosition from "./verticalPosition.vue";
import positionList from "./positionList.vue";

const CYCLE_COST = [
  {
    title: "账单起止时间",
    dataIndex: "area_range",
    key: "area_range",
    width: 350,
  },
  {
    title: "实际天数",
    dataIndex: "days",
    key: "days",
  },
  {
    title: "费用类型",
    dataIndex: "billCostTypeName",
    key: "billCostTypeName",
  },
  {
    title: "单价",
    dataIndex: "unitTxt",
    key: "unitTxt",
  },
  {
    title: "应收时间",
    dataIndex: "payDate",
    key: "payDate",
  },
  {
    title: "应收金额",
    dataIndex: "countPrice",
    key: "countPrice",
  }
]

const ONE_TIME_EXPENSES = [
  {
    title: "账单起止时间",
    dataIndex: "area_range",
    key: "area_range",
    width: 350,
  },
  {
    title: "费用类型",
    dataIndex: "billCostTypeName",
    key: "billCostTypeName",
  },
  {
    title: "单价",
    dataIndex: "unitTxt",
    key: "unitTxt",
  },
  {
    title: "应收时间",
    dataIndex: "payDate",
    key: "payDate",
  },
  {
    title: "应收金额",
    dataIndex: "countPrice",
    key: "countPrice",
  }
]

export default defineComponent({
  emits: ["close"],
  components: {
    PlusOutlined,
    ChooseHousingResources,
    CheckedHousingResources,
    QuestionCircleOutlined,
    FieldTimeOutlined,
    SwapRightOutlined,
    verticalPosition,
    positionList,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    standardInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    charges_id: {
      type: Number,
      default: 0,
    },
    roomDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props, context) {
    const formRef = ref();
    const state = reactive({
      firstRequest: true,
      showSelectedPosition: false,
      parkSpaceList: [],
      confirmLoading: false,
      costTypeList: [],
      refreshSelect: true,
      includeSelfArea: "",
      defaultCheckedIds: {},
      clauseType: "property", //条款类型
      showSelectedHouse: false,

      roomList: [],
      topList: [],

      standardForm: {
        pay_cycle: null,
        fee_type: [],
        standard_name: "",
        price_or_amount: "",
        unit_charging: "yuan_per_day",
        payment_time: null,
        daily_unit_price_and_month_rule: "month_day",
        divide_method: "phase_on",
        pay_date_action: "delay",
        pay_date_days: null,
        pay_date_action_type: "natural_day",
        start_date: "",
        end_date: "",
      },
      rules: {
        pay_cycle: [ { required: true, message: "请输入", }, ],
        fee_type: [ { required: true, message: "请输入", }, ],
        standard_name: [ { required: true, message: "请输入", }, ],
        price_or_amount: [ { required: true, message: "请输入", }, ],
        unit_charging: [ { required: true, message: "请选择", }, ],
        payment_time: [ { required: true, message: "请选择", }, ],
        number: [ { required: true, message: "请选择", }, ],
        daily_unit_price_and_month_rule: [ { required: true, message: "请选择", }, ],
        divide_method: [ { required: true, message: "请选择", }, ],
        pay_date_action: [ { required: true, message: "请输入", }, ],
        pay_date_days: [ { required: true, message: "请输入", }, ],
      },

      tableLoading: false,
      pagination: {
        current: 1,
        pagiSize: 10,
        showSizeChanger: true,
        showTotal: (total, range) => `总数: ${total} 个`,
      },
      tableList: [],
      tableColumns: [],
      affectDivideMethod: {},
      dailyRuleSelect: {},
      monthDivideMethodArr: {},
      payActionDayArr: {},
      payDateSelect: {},
      unitYuanRelation: {},
      unitOnceRelation: {},
      extionsInfo: {},
      expandedRowKeys: [],

      chooseHousingDisabled: false, //是否禁用房源选择组件
      butloading : false,   //是否正在请求房间
      constructloading : false,   //房间的建筑面积是否为0
      isDemonstrate: true
    });

    const onClose = () => {
      context.emit("close");
      clearForm();
      formRef.value.resetFields();
    };

    const dateRanges = computed(() => ({
      '当日': props.standardInfo.valid_time
        ? moment().isBefore(props.standardInfo.valid_time, "day")
          ? [
              moment(props.standardInfo.valid_time),
              moment(props.standardInfo.valid_time),
            ]
          : [moment(), moment()]
        : [moment(), moment()],
      '未来七天': props.standardInfo.valid_time
        ? moment().isBefore(props.standardInfo.valid_time, "day")
          ? [
              moment(props.standardInfo.valid_time),
              moment(props.standardInfo.valid_time)
                .add(1, "weeks")
                .subtract(1, "days"),
            ]
          : [moment(), moment().add(1, "weeks").subtract(1, "days")]
        : [moment(), moment().add(1, "weeks").subtract(1, "days")],
      '未来一月': props.standardInfo.valid_time
        ? moment().isBefore(props.standardInfo.valid_time, "day")
          ? [
              moment(props.standardInfo.valid_time),
              moment(props.standardInfo.valid_time)
                .add(1, "months")
                .subtract(1, "days"),
            ]
          : [moment(), moment().add(1, "months").subtract(1, "days")]
        : [moment(), moment().add(1, "months").subtract(1, "days")],
      '未来三月': props.standardInfo.valid_time
        ? moment().isBefore(props.standardInfo.valid_time, "day")
          ? [
            moment(props.standardInfo.valid_time),
            moment(props.standardInfo.valid_time)
              .add(3, "months")
              .subtract(1, "days"),
          ]
          : [moment(), moment().add(3, "months").subtract(1, "days")]
        : [moment(), moment().add(3, "months").subtract(1, "days")],
      '未来半年': props.standardInfo.valid_time
        ? moment().isBefore(props.standardInfo.valid_time, "day")
          ? [
            moment(props.standardInfo.valid_time),
            moment(props.standardInfo.valid_time)
              .add(6, "months")
              .subtract(1, "days"),
          ]
          : [moment(), moment().add(6, "months").subtract(1, "days")]
        : [moment(), moment().add(6, "months").subtract(1, "days")],
      '未来一年': props.standardInfo.valid_time
        ? moment().isBefore(props.standardInfo.valid_time, "day")
          ? [
              moment(props.standardInfo.valid_time),
              moment(props.standardInfo.valid_time)
                .add(1, "years")
                .subtract(1, "days"),
            ]
          : [moment(), moment().add(1, "years").subtract(1, "days")]
        : [moment(), moment().add(1, "years").subtract(1, "days")],
    }));

    const clearForm = () => {
      state.village_name = [];
      state.tableList = [];
      (state.firstRequest = true), (state.showSelectedHouse = false);
      state.confirmLoading = false;
      state.tableLoading = false;
      state.bill_cost_type = {};
      state.roomList = [];
      state.parkSpaceList = [];
      state.bill_cost_type_id = null;
      state.showSelectedPosition = false;
      state.standardForm = {
        pay_cycle: null,
        fee_type: [],
        standard_name: "",
        price_or_amount: "",
        unit_charging: "yuan_per_day",
        payment_time: null,
        daily_unit_price_and_month_rule: "month_day",
        divide_method: "phase_on",
        pay_date_action: "delay",
        pay_date_days: null,
        pay_date_action_type: "natural_day",
        start_date: "",
        end_date: "",
      };
    };

    const handleSelectChange = (value, type) => {
      if (type == "month_rule" && value == "month_day") {
        state.standardForm["divide_method"] = "phase_on";
      }

      if (type == "unit_charging") {
        state.refreshSelect = false;
        nextTick(() => {
          state.refreshSelect = true;
        });
      }

      if (type == "pay_date_action") {
        if (value == "specify_date") {
          state.standardForm["pay_date_action_type"] = "from_month";
        } else {
          state.standardForm["pay_date_action_type"] = "natural_day";
        }
      }
    };

    const handleSubmit = () => {
      formRef.value.validate().then(() => {
        if (
          state.roomList &&
          state.roomList.length == 0 &&
          props.standardInfo.bind_object == 1
        ) {
          message.warn("请先选择房间");
          return;
        }
        if (
          state.parkSpaceList &&
          state.parkSpaceList.length == 0 &&
          props.standardInfo.bind_object == 2
        ) {
          message.warn("请先选择车位");
          return;
        }
        getParams(state.standardForm, 0);
      });
    };

    const changeHouseCard = () => {
      state.showSelectedHouse = !state.showSelectedHouse;
    };

    const getRoomList = (result) => {
      state.roomList = result.roomList;
      if (state.roomList.length > 0) {
        state.standardForm.village_id = state.roomList[0].extra.village_id;
      }
      if (props.standardInfo && props.standardInfo.id) {
        getfeetype()
      }
      for (let i = 0 ; i < state.roomList.length ; i++){
        if(!state.roomList[i].build_area || state.roomList[i].build_area == 0){
          state.constructloading = true
          message.warning(`您选择的${state.roomList[i].extra.village_name}/${state.roomList[i].extra.build_name}/
                     ${state.roomList[i].layer_name}/${state.roomList[i].room_name}建筑面积为0㎡，请您重新选择！`);
          return
        }else {
          state.constructloading = false
        }
      }
    };

    const getfeetype = () => {
      getCostCategory().then((res) => {
        if (state.standardForm["fee_type"]) {
          let options = res.find(
              (v) => v.value == state.standardForm["fee_type"][0]
          );
          getCostTypeSub([options]).then(() => {
            getParams(state.standardForm, 1);
          });
        }
      });
    }

    const getloading = (index) => {
      if(index == 1){
        state.butloading = true
      }else {
        state.butloading = false
      }
    }

    const setPosition = (result) => {
      state.parkSpaceList = result.parkSpaceList;
      state.village_name = result.village_name;
    };

    const getCostCategory = () => {
      return new Promise((resolve, reject) => {
        request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
          if (res.list) {
            state.costTypeList = res.list.map((item) => ({
              label: item.name,
              value: item.id,
              isLeaf: false,
            }));
            resolve(state.costTypeList);
          }
        });
      });
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      return new Promise((resolve, reject) => {
        request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption.value,
            status: 1,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                id: item.id,
                label: item.name,
                value: item.cost_type,
                isLeaf: true,
              }));
              state.costTypeList = [...state.costTypeList];
              resolve(state.costTypeList);
            }
          });
      });
    };

    const getTableList = (params) => {
      state.tableLoading = true;
      state.tableList = [];
      state.extionsInfo = {};
      if(params.build_area){
        state.isDemonstrate = false
      }else{
        state.isDemonstrate = true
      }
      request
        .post("/org", "/standard/charge/generateBill", params)
        .then((res) => {
          state.firstRequest = false;
          if (params.isDemo == 0) {
            state.confirmLoading = false;
            message.success(res.msg);
            context.emit("close", true);
            clearForm();
            formRef.value.resetFields();
          }
          state.tableLoading = false;
          state.tableList = res.divisionsDemo || [];
          state.extionsInfo = res.extionsInfo || [];
          state.tableList.map((item, index) => {
            item.key = index;
            if (item.months && item.months.length > 0) {
              item.children = item.months;
              item.children.map((sub_item, sub_index) => {
                sub_item.key = index + "-" + sub_index;
                sub_item.billCostTypeName =
                  "本月自然天数（" + sub_item.daysInMonth + "）";
                sub_item.unitTxt = sub_item.dayPrice;
              });
            }
            item.type = "parent";
          });
        })
        .catch((err) => {
          state.tableLoading = false;
          if (params.isDemo == 0) {
            state.confirmLoading = false;
          }
        });
    };

    const getCascaderList = () => {
      request.get("/org", "/standard/charge/cascader").then((res) => {
        state.affectDivideMethod = res.affectDivideMethod;
        state.dailyRuleSelect = res.dailyRuleSelect;
        state.monthDivideMethodArr = res.monthDivideMethodArr;
        state.payActionDayArr = res.payActionDayArr;
        state.payDateSelect = res.payDateSelect;
        state.unitYuanRelation = res.unitYuanRelation;
        state.unitOnceRelation = res.unitOnceRelation;
      });
    };

    const handleDateChange = (value, valueStr) => {
      state.standardForm.start_date = valueStr[0];
      state.standardForm.end_date = valueStr[1];
    };

    const handleDateChangees = (value, valueStr) => {
      state.standardForm.start_date = valueStr
      state.standardForm.end_date = valueStr
    };
    const handleTableExtend = (expend, record) => {
      if (!record.type) return;
      if (state.expandedRowKeys.indexOf(record.key) != -1) {
        let index = state.expandedRowKeys.indexOf(record.key);
        state.expandedRowKeys.splice(index, 1);
      } else {
        state.expandedRowKeys.push(record.key);
      }
    };

    const handleClickRow = (record, index) => {
      return {
        onClick: (event) => {
          handleTableExtend(false, record);
        },
      };
    };

    const disabledDate = (current) => {
      if (props.standardInfo.valid_time) {
        return (
          current < moment(props.standardInfo.valid_time).subtract(0, "day")
        );
      } else {
        return current < moment().subtract(0, "day");
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getCascaderList();

          // 锁定房源
          if (props.roomDetail && props.roomDetail.id) {
            console.log("props.roomDetail", props.roomDetail);
            state.chooseHousingDisabled = true;
            state.defaultCheckedIds = {
              villageId: props.roomDetail.village_id,
              buildId: props.roomDetail.build_id,
              layerId: props.roomDetail.layer_id,
              roomId: props.roomDetail.id,
            };
          }
        }

        if (val && props.standardInfo && props.standardInfo.id) {
          let unitPrice = props.standardInfo.unit_price;
          if (props.standardInfo.unitText) {
            unitPrice =
              props.standardInfo.unit_price +
              "（x" +
              props.standardInfo.unitText +
              "）";
          }
          state.topList = [
            {
              label: "收费标准名称",
              value: props.standardInfo.name,
            },
            {
              label: "计费模式",
              value: props.standardInfo.modeText
                ? props.standardInfo.modeText
                : "暂无",
            },
            {
              label: "单价(元)",
              value: unitPrice,
            },
            {
              label: "标准生效日期",
              value: props.standardInfo.valid_time,
            },
            {
              label: "标准失效日期",
              value: props.standardInfo.expire_time,
            },
            {
              label: "状态",
              value: props.standardInfo.status == 1 ? "生效中" : "已失效",
            },
          ];
          state.standardForm.charges_id = props.standardInfo.id;
          if (props.standardInfo.village_id) {
            state.standardForm.village_id = props.standardInfo.village_id;
          }
          state.standardForm.standard_name = props.standardInfo.name;
          state.standardForm.price_or_amount = props.standardInfo.unit_price;
          state.standardForm.start_date = props.standardInfo.valid_time;
          state.standardForm.pay_date_action =
            props.standardInfo.pay_date_action;
          state.standardForm.pay_date_days = props.standardInfo.pay_date_days;
          state.standardForm.pay_date_action_type =
            props.standardInfo.pay_date_action_type;
          state.standardForm.pay_cycle = props.standardInfo.pay_cycle;
          state.standardForm.unit_charging = props.standardInfo.unit_charging;
          state.standardForm.cash_type = props.standardInfo.cash_type;
          state.standardForm.mode = props.standardInfo.mode;
          state.standardForm.number = 1 ;
          if (props.standardInfo.bill_cost_type) {
            state.standardForm.unit_charging = props.standardInfo.unit_charging;
            state.standardForm.daily_unit_price_and_month_rule =
              props.standardInfo.daily_unit_price_and_month_rule;
            state.standardForm.divide_method = props.standardInfo.divide_method;
            state.standardForm["fee_type"] =
              props.standardInfo.bill_cost_type["fee_type"];
            state.standardForm.bill_cost_type_id =
              props.standardInfo.bill_cost_type_id;
            state.standardForm["bill_cost_type"] =
              props.standardInfo.bill_cost_type;
          }

          if(state.standardForm.cash_type == 1){
            state.tableColumns = CYCLE_COST
          }else {
            state.tableColumns = ONE_TIME_EXPENSES
          }

          let nowTime = moment();
          let starndardValidTime = moment(props.standardInfo.valid_time);
          if (nowTime.isBefore(starndardValidTime)) {
            console.log("-------->>当前标准还未生效");
            nowTime = props.standardInfo.valid_time;
          }

          let date1 = moment(props.standardInfo.valid_time);
          let date2 = moment(props.standardInfo.expire_time);

          let diff = date2.diff(date1, "years");
          let BigOneYear = true;
          if (diff >= 1) {
            BigOneYear = true;
          } else {
            BigOneYear = false;
          }

          if (props.standardInfo.expire_time == "2099-12-12") {
            if(state.standardForm.cash_type == 1){
              state.standardForm.payment_time = [
                moment(nowTime),
                moment(nowTime).add(1, "years").subtract(1, "days"),
              ];
            }else {
              state.standardForm.payment_time = [
                moment(nowTime),
                moment(nowTime),
              ];
            }


            state.standardForm.start_date = state.standardForm.payment_time[0].format("YYYY-MM-DD");
            state.standardForm.end_date = state.standardForm.payment_time[1].format("YYYY-MM-DD");

          } else {
            state.standardForm.end_date = props.standardInfo.expire_time;

            if (BigOneYear) {
              if(state.standardForm.cash_type == 1){
                state.standardForm.payment_time = [
                  moment(nowTime),
                  moment(nowTime).add(1, "years").subtract(1, "days"),
                ];
              }else {
                state.standardForm.payment_time = [
                  moment(nowTime),
                  moment(nowTime),
                ];
                state.standardForm.start_date = state.standardForm.payment_time[0].format("YYYY-MM-DD");
                state.standardForm.end_date = state.standardForm.payment_time[1].format("YYYY-MM-DD");
              }
            } else {
              if(state.standardForm.cash_type == 1){
                state.standardForm.payment_time = [
                  moment(nowTime),
                  moment(props.standardInfo.expire_time),
                ];
              }else {
                state.standardForm.payment_time = [
                  moment(nowTime),
                  moment(nowTime),
                ];
                state.standardForm.start_date = state.standardForm.payment_time[0].format("YYYY-MM-DD");
                state.standardForm.end_date = state.standardForm.payment_time[1].format("YYYY-MM-DD");
              }
            }
          }

          getfeetype()
        }
      }
    );

    const getParams = (val, isDemo) => {
      let params = {};
      Object.assign(params, val);
      Reflect.deleteProperty(params, "payment_time");
      if (isDemo == 1) {
        Reflect.deleteProperty(params, "village_id");
      }
      if (val["fee_type"][1]) {
        let index = state.costTypeList.findIndex(
          (v) => v.value == val["fee_type"][0]
        );
        if (index != -1) {
          if (!state.costTypeList[index].children) return;
          state.costTypeList[index].children.map((item) => {
            if (item.value == val["fee_type"][1]) {
              params.bill_cost_type_id = item.id;
              params.bill_cost_type = {};
              params.bill_cost_type["name"] = item.label;
              params.bill_cost_type["cost_type"] = item.value;
              params.bill_cost_type["bigName"] =
                state.costTypeList[index].label;
              Reflect.deleteProperty(params, "fee_type");
              if (params.daily_unit_price_and_month_rule == "30_day") {
                Reflect.deleteProperty(params, "divide_method");
              }
              let flag = true;
              for (let key in params) {
                if (!params[key]) {
                  flag = false;
                }
              }
              if (flag) {
                params.isDemo = isDemo;
                if (isDemo == 0) {
                  if (props.standardInfo.bind_object == 1) {
                    params.roomList = state.roomList;
                  } else if (props.standardInfo.bind_object == 2) {
                    params.parkSpaceList = state.parkSpaceList;
                    params.village_name = state.village_name;
                  }
                  state.confirmLoading = true;
                }
                if (props.charges_id) {
                  params.charges_id = props.charges_id;
                }
                console.log(params,'111111')
                if(params.mode==2&&state.roomList.length==1){
                  params.build_area = state.roomList[0].build_area
                }
                getTableList(params);
              }
            }
          });
        } else if (props.standardInfo.bill_cost_type) {
          params.isDemo = isDemo;
          if (props.charges_id) {
            params.charges_id = props.charges_id;
          }
          if (params.daily_unit_price_and_month_rule == "30_day") {
            Reflect.deleteProperty(params, "divide_method");
          }
          if(params.mode==2&&state.roomList.length==1){
            params.build_area = state.roomList[0].build_area
          }
          console.log(params,'222222')
          getTableList(params);
        }
      }
    };

    watch(
      () => state.standardForm,
      (val) => {
        if (state.firstRequest) return;
        if (
          props.visible &&
          formRef.value &&
          (state.standardForm.pay_cycle ||
            (state.standardForm.fee_type &&
              state.standardForm.fee_type.length) ||
            state.standardForm.pay_date_days)
        ) {
          formRef.value
            .validate()
            .then(() => {
              getParams(val, 1);
              
            })
            .catch((err) => {
              getParams(val, 1);
            });
        } else if (
          !formRef.value &&
          (state.standardForm.pay_cycle ||
            (state.standardForm.fee_type &&
              state.standardForm.fee_type.length) ||
            state.standardForm.pay_date_days) &&
          props.visible
        ) {
          getParams(val, 1);
        }
      },
      {
        deep: true,
      }
    );

    return {
      disabledDate,
      onClose,
      handleSubmit,
      changeHouseCard,
      getRoomList,
      getloading,
      handleSelectChange,
      getCostTypeSub,
      formRef,
      handleDateChange,
      handleClickRow,
      handleTableExtend,
      setPosition,
      handleDateChangees,
      getfeetype,
      ...toRefs(state),
      dateRanges,
      CYCLE_COST,
      ONE_TIME_EXPENSES,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.ant-table-placeholder) {
  border-bottom: none !important;
}

:deep(.checked-house),
:deep(.choose-housing),
:deep(.vertical_position),
:deep(.position_list) {
  padding-bottom: 100px;

  &::-webkit-scrollbar {
    width: 7px; //y轴滚动条粗细
    height: 0px; //x轴滚动条粗细
    border-bottom: 1px solid #7b7b7b;
  }

  //滚动条里面的小方块，能上下左右移动（取决于是垂直滚动条还是水平滚动条）
  &::-webkit-scrollbar-thumb {
    border-radius: 8px;
    min-height: 120px; // 滑块高度
    -webkit-box-shadow: inset 0 0px 6px rgba(0, 0, 0, 0.2);
    background: rgba(97, 108, 114, 0.1);
  }
}

//表格体的滚动条设置
:deep(.ant-table-body) {
  position: absolute;
  border-right: #2f2f2f;

  //滚动条整体部分
  &::-webkit-scrollbar {
    width: 7px; //y轴滚动条粗细
    height: 0px; //x轴滚动条粗细
    border-bottom: 1px solid #7b7b7b;
  }

  //滚动条里面的小方块，能上下左右移动（取决于是垂直滚动条还是水平滚动条）
  &::-webkit-scrollbar-thumb {
    border-radius: 8px;
    min-height: 120px; // 滑块高度
    -webkit-box-shadow: inset 0 0px 6px rgba(0, 0, 0, 0.2);
    background: rgba(97, 108, 114, 0.1);
  }
}

:deep(
    .ant-table-tbody
      > tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)
      > td
  ) {
  font-weight: bold;
}

.drawer_con {
  width: 100%;

  .top_con {
    display: flex;
    justify-content: space-between;

    .left_form {
      flex: 1;

      .standard_con {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        transform: translateY(-10px);

        .standard_list {
          width: 33.3%;
          flex-shrink: 0;
          display: flex;
          margin-top: 10px;

          .left_label {
            color: #666;
            font-size: 14px;
          }

          .right_value {
            color: #999;
            font-size: 14px;
          }
        }
      }

      .form_con {
        .form_title {
          width: 100%;
          padding: 15px 0;
          border-bottom: 1px dashed #d7d7d7;
          font-size: 15px;
          color: #333;
          margin-bottom: 15px;
          font-weight: bolder;
        }

        .form_item {
          display: flex;
        }
      }
    }

    .right_single {
      width: 380px;
      height: 452px;
      padding-left: 30px;
      overflow-y: hidden;
      overflow-x: hidden;

      &::-webkit-scrollbar {
        width: 0;
      }

      .form_title {
        width: 100%;
        padding: 15px 0;
        border-top: 1px dashed #999;
        border-bottom: 1px dashed #999;
        font-size: 15px;
        color: #333;
        margin-bottom: 15px;
        display: flex;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        height: 60px;

        .left_label {
          font-size: 15px;
          color: #333;
        }

        .right_con {
          flex-shrink: 0;
        }
      }
    }
  }

  .bottom_con {
    min-height: 100px;
    width: 100%;
    padding-bottom: 50px;
    .form_title {
      width: 100%;
      padding: 15px 0;
      border-bottom: 1px dashed #d7d7d7;
      font-size: 15px;
      color: #333;
      margin-bottom: 15px;
      font-weight: bolder;
    }

    .table_footer {
      width: 1338px;
      display: flex;
      background-color: #fafafa;
      padding: 20px;
      align-items: center;
      justify-content: space-between;
      position: fixed;
      right: 17px;
      bottom: 53px;
      .footer_left {
        font-size: 14px;
        color: #333;
        font-weight: 600;
      }

      .footer_right {
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .footer_item {
          display: flex;
          margin-right: 30px;
        }
      }
    }
  }
}
</style>
